//
//  HTGoodsSourceViewController.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/26.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTGoodsSourceViewController.h"
#import "HTGoodSourceCell.h"
#import "HTGoodSourceTypeTwoCell.h"
#import "HTGoodsDetialViewController.h"
#import "UIView+Layout.h"
#import "HTMLocationManager.h"
#import "HTGoodSearchModel.h"
#import "HTRefreshMoreModel.h"

//弹框
//出发地，目的地
#import "HTAreaChoiceView.h"
//车长车型
#import "HTTruckTypeView.h"

#import "HTLoginVC.h"

@interface HTGoodsSourceViewController ()<UITableViewDelegate,UITableViewDataSource,HTAreaChoiceViewDelegate,HTTruckTypeViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;
@property (weak, nonatomic) IBOutlet UIView *truckTypeView;
@property (weak, nonatomic) IBOutlet UIImageView *truckTypeImageView;
@property (weak, nonatomic) IBOutlet UILabel *truckTypeLabel;
@property (weak, nonatomic) IBOutlet UIView *startView;
@property (weak, nonatomic) IBOutlet UIImageView *startImageView;
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
@property (weak, nonatomic) IBOutlet UIView *destiView;
@property (weak, nonatomic) IBOutlet UIImageView *destiImageView;
@property (weak, nonatomic) IBOutlet UILabel *destiLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

//弹框
@property (nonatomic,strong) HTAreaChoiceView *areaChoiceView;
@property (nonatomic,strong) HTTruckTypeView *truckLengthTypeView;

#pragma mark --- 数据处理
//弹框数据
@property (nonatomic,strong) NSMutableArray *selectedLengthData;
@property (nonatomic,strong) HTTruckTypeModel *selectedTruckType;
@property (nonatomic,strong) HTTruckTypeModel *selectedGoodsType;
@property (nonatomic,assign) BOOL isLessThanTruck;

@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) NSString *startAddress;
@property (nonatomic,strong) NSString *endAddress;

@property (nonatomic,assign) NSInteger pageNumber;
@property (nonatomic,strong) HTRefreshMoreModel *refreshMoreModel;

@property (nonatomic,strong) NSString *isauitd;

@end

@implementation HTGoodsSourceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configTableView];
    [self tapGesture];
    [self loadLocation];
    self.isauitd = @"";
    self.endAddress = self.destiLabel.text;
    self.pageNumber = 1;
}
#pragma mark --- 定位
- (void)loadLocation{
    if ([[HTMLocationManager singleInstance] getCurrentAddress].length <= 0) {
        //定位请求
        [self requestLocation];
        self.startLabel.text = @"北京";
    }else{
        self.startLabel.text = [[HTMLocationManager singleInstance] getCurrentAddress];
    }
    self.startAddress = self.startLabel.text;
    self.startLabel.textColor = [UIColor blackColor];
}
- (void)requestLocation{
    [[HTMLocationManager singleInstance]requestLocationCompletionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            if (error.code == AMapLocationErrorLocateFailed)
            {
                [HTShowUtil showMessage:@"定位失败"];
                return;
            }
        }
        if (regeocode)
        {
            if (regeocode.city == nil || regeocode.city.length <= 0) {
                self.startLabel.text = @"北京";
                self.startAddress = self.startLabel.text;
                return;
            }
            [HTMLocationManager singleInstance].currentCity = regeocode.city;
            [HTMLocationManager singleInstance].currentProvince = regeocode.province;
            self.startLabel.text =  [[HTMLocationManager singleInstance]getCurrentAddress];
            self.startAddress = self.startLabel.text;
            [self netLoadPostLocationWithAddress:regeocode.formattedAddress lat:[NSString stringWithFormat:@"%f",location.coordinate.latitude]  lng:[NSString stringWithFormat:@"%f",location.coordinate.longitude]];
        }
    }];
}
#pragma mark --- 界面绘制
- (void)tapGesture{
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.startView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.destiView addGestureRecognizer:tap2];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.truckTypeView addGestureRecognizer:tap3];
}
- (void)configTableView{
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT;
    [self setTabViewWithIndex:3];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.width = kHTScreenWidth;
    self.tableView.backgroundColor = kBackgroundColor;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTGoodSourceCell" bundle:nil] forCellReuseIdentifier:goodSourceCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTGoodSourceTypeTwoCell" bundle:nil] forCellReuseIdentifier:goodSourceCellTwo];
    self.tableView.estimatedRowHeight =0;
    self.tableView.estimatedSectionHeaderHeight =0;
    self.tableView.estimatedSectionFooterHeight =0;
    [self configTableHeader];
    [self configTableFooter];
    self.tableView.mj_header = self.header;
    self.tableView.mj_footer = self.footer;
    self.noDataView = [[HTNoDataView alloc]initWithFrame:self.tableView.bounds];
    self.noDataView.showMessage = @"暂无货源";
}

#pragma mark --- lazyLoad
//货源数据
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark --- tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
      [tableView tableViewDisplayView:self.noDataView ifNecessaryForRowCount:self.dataSource.count];
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     HTGoodSearchModel *model = self.dataSource[indexPath.row];
    if ((model.addtype == nil || model.addtype.length <= 0 ) && (model.strattime == nil || model.strattime.length <= 0)) {
         return 135;
    }else{
         return 155;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTGoodSearchModel *model = self.dataSource[indexPath.row];
    if (model.pricers== nil ||model.pricers.length <= 0) {
        HTGoodSourceTypeTwoCell *cell = (HTGoodSourceTypeTwoCell *)[tableView dequeueReusableCellWithIdentifier:goodSourceCellTwo forIndexPath:indexPath withController:self];
        cell.searchModel = model;
        cell.isauitd = self.isauitd;
        return cell;
    }else{
        HTGoodSourceCell *cell = (HTGoodSourceCell*) [tableView dequeueReusableCellWithIdentifier:goodSourceCell forIndexPath:indexPath withController:self];
        cell.searchModel = model;
        cell.isauitd = self.isauitd;
        return cell;
    }
}
#pragma mark --- 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([HTMUserDefaultUtil isLogin]) {
        if (![self.isauitd isEqualToString:@"1"]) {
            [HTShowUtil showMessage:@"您还未认证成功，请先认证"];
            return;
        }
        HTGoodSearchModel *model = self.dataSource[indexPath.row];
        HTGoodsDetialViewController *detial = [[HTGoodsDetialViewController alloc]init];
        detial.searchModel = model;
        [self.navigationController pushViewController:detial animated:YES];
    }else{
        HTLoginVC *login = [[HTLoginVC alloc]init];
        [self.navigationController pushViewController:login animated:YES];
    }
   
}
//点击TabView,切换出发地，目的地，车长车型弹框
- (void)didTapGesture:(UITapGestureRecognizer *)sender{
    
    switch ([sender view].tag) {
        case 111://出发地
        {
            [self removeTruckLengthTypeView];
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeStart) {//点击了同一个,收起
                [self removeAreaChoiceView];
                //设置tab选中状态
                [self setTabViewWithIndex:3];
                return;
            }
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeDestination) {//同一个View，但是类型不同，刷新数据
                self.areaChoiceView.areaChoiceType = HTAreaChoiceTypeStart;
                [self.areaChoiceView reloadAllData];
                [self setTabViewWithIndex:0];
                return;
            }
            [self setupAreaViewWithType:HTAreaChoiceTypeStart];
             [self setTabViewWithIndex:0];
        
        }
            break;
        case 112://终点
        {
            [self removeTruckLengthTypeView];
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeDestination) {//点击了同一个,收起
                [self removeAreaChoiceView];
                [self setTabViewWithIndex:3];
                return;
            }
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeStart) {//同一个View，但是类型不同，刷新数据
                self.areaChoiceView.areaChoiceType = HTAreaChoiceTypeDestination;
                [self.areaChoiceView reloadAllData];
                [self setTabViewWithIndex:1];
                return;
            }
            [self setupAreaViewWithType:HTAreaChoiceTypeDestination];
             [self setTabViewWithIndex:1];
           
        }
            break;
        case 114://车型车长
        {
            [self removeAreaChoiceView];
            if (!self.truckLengthTypeView) {
                [self setupTruckLengthTypeView];
                [self setTabViewWithIndex:2];
            }else{
                [self removeTruckLengthTypeView];
                [self setTabViewWithIndex:3];
            }
        }
            break;
        default:
            break;
    }
}
//选中起始地，目的地，车长车型部分
- (void)setTabViewWithIndex:(NSInteger)index{
    switch (index) {
        case 0://起始地
        {
            [self setTabViewSelected:YES withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:NO withImageView:self.destiImageView withLabel:self.destiLabel];
            [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        case 1://目的地
        {
            [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:YES withImageView:self.destiImageView withLabel:self.destiLabel];
            [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        case 2://车长车型
        {
            [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:NO withImageView:self.destiImageView withLabel:self.destiLabel];
            [self setTabViewSelected:YES withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        case 3://均不选中
        {
            [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:NO withImageView:self.destiImageView withLabel:self.destiLabel];
            [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        default:
            break;
    }
}
- (void)setTabViewSelected:(BOOL)selected withImageView:(UIImageView *)imageView withLabel:(UILabel *)label{
    if (selected) {
        imageView.image = [[UIImage imageNamed:@"arrow_solid_up"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = kBlueColor;
        label.textColor = kBlueColor;
    }else{
       imageView.image = [[UIImage imageNamed:@"arrow_solid_down"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = [UIColor blackColor];
        label.textColor = [UIColor blackColor];
    }
}

#pragma mark -------- 处理弹框选择出发地目的地的操作
//出发地目的地弹框View
- (void)setupAreaViewWithType:(HTAreaChoiceType)type{
    if (!self.areaChoiceView) {
        self.areaChoiceView = [[HTAreaChoiceView alloc]initWithFrame:CGRectMake(0, self.startView.bottom, kHTScreenWidth, kHTScreenHeight - self.startView.bottom - kHTNavicationBarAndStatusBar)];
        self.areaChoiceView.areaChoiceType = type;
        self.areaChoiceView.delegate = self;
        __weak __typeof(self)weakSelf = self;
        self.areaChoiceView.blockCallBack = ^{
            [weakSelf removeAreaChoiceView];
            [weakSelf setTabViewWithIndex:3];
        };
        [self.view addSubview:self.areaChoiceView];
    }
}
//移除弹框，出发地目的地
- (void)removeAreaChoiceView{
    if (self.areaChoiceView) {
        [self.areaChoiceView removeFromSuperview];
        self.areaChoiceView = nil;
    }
}
//代理
- (void)didChoiceItemWithAreaModel:(HTAreaModel *)areaModel currentIndex:(NSInteger)currentIndex areaChoiceType:(HTAreaChoiceType)areaChoiceType{
    if (areaModel.areaType == HTAreaTypeNo || areaModel.areaType == HTAreaTypeArea) {
        
        [self removeAreaChoiceView];
        [self setTabViewWithIndex:3];
        NSString *place = [HTUtils placePostStringWith:areaModel];
        if (areaChoiceType == HTAreaChoiceTypeStart) {//出发地
            self.startLabel.text = areaModel.title;
            self.startAddress = place;
            //调用刷新网络请求
            [self.tableView.mj_header beginRefreshing];
        }
        if (areaChoiceType == HTAreaChoiceTypeDestination) {//目的地
            self.destiLabel.text = areaModel.title;
            self.endAddress = place;
            //调用刷新网络请求
            [self.tableView.mj_header beginRefreshing];
        }
    }
  }
- (void)didChoiceItemWithHistory:(HTAreaModel *)areaModel areaChoiceType:(HTAreaChoiceType)areaChoiceType{
    //调用刷新网络请求
    [self removeAreaChoiceView];
    [self setTabViewWithIndex:3];
    NSString *place = [HTUtils placePostStringWith:areaModel];
    if (areaChoiceType == HTAreaChoiceTypeStart) {//出发地
        self.startLabel.text = areaModel.title;
        self.startAddress = place;
        //调用刷新网络请求
        [self.tableView.mj_header beginRefreshing];
    }
    if (areaChoiceType == HTAreaChoiceTypeDestination) {//目的地
        self.destiLabel.text = areaModel.title;
        self.endAddress = place;
        //调用刷新网络请求
        [self.tableView.mj_header beginRefreshing];
    }
}
#pragma mark --- 处理弹框车长车型
- (void)setupTruckLengthTypeView{
    if (!self.truckLengthTypeView) {
        self.truckLengthTypeView = [[HTTruckTypeView alloc]initWithFrame:CGRectMake(0, self.startView.bottom, kHTScreenWidth, kHTScreenHeight - self.startView.bottom - kHTNavicationBarAndStatusBar)];
        self.truckLengthTypeView.delegate = self;
        self.truckLengthTypeView.selectedGoodType = self.selectedGoodsType;
        self.truckLengthTypeView.selectedTruckType  = self.selectedTruckType;
        self.truckLengthTypeView.selectedLengths = self.selectedLengthData;
        self.truckLengthTypeView.isLessThanTruck= self.isLessThanTruck;
        [self.truckLengthTypeView reloadContentData];
        __weak __typeof(self)weakSelf = self;
        self.truckLengthTypeView.blockCallBack = ^{
            [weakSelf removeTruckLengthTypeView];
            [weakSelf setTabViewWithIndex:3];
        };
        [self.view addSubview:self.truckLengthTypeView];
    }
}
//移除弹框，车长车型
- (void)removeTruckLengthTypeView{
    if (self.truckLengthTypeView) {
        [self.truckLengthTypeView removeFromSuperview];
        self.truckLengthTypeView = nil;
    }
}
- (void)didClickConformWithLengths:(NSMutableArray *)lengthsData TruckType:(HTTruckTypeModel *)truckType GoodType:(HTTruckTypeModel *)goodsType isLessThanTruck:(BOOL)isLessThanTruck{
    self.selectedLengthData = lengthsData;
    self.selectedTruckType = truckType;
    self.selectedGoodsType = goodsType;
    self.isLessThanTruck = isLessThanTruck;
    NSString *total = @"";
    total = [NSString stringWithFormat:@"%@,%@",total,[HTUtils sortLengthDataDisplayStringWithArray:lengthsData]];
    NSInteger index = 1;
    if ([total isEqualToString:@",不限车长"]) {
        total = @"";
        index = 0;
    }
    if (!(truckType.truckTypeModelType == TruckTypeModelTypeUnlimited)) {
        if (index < 2) {
            total = [NSString stringWithFormat:@"%@,%@",total,truckType.title];
            index++;
        }
    }
    if (!(goodsType.truckTypeModelType == TruckTypeModelTypeUnlimited)) {
        if (index < 2) {
            total = [NSString stringWithFormat:@"%@,%@",total,goodsType.title];
            index ++;
        }
    }
    if (total.length <= 0) {
        total = @"车长车型";
    }else{
        total = [total substringFromIndex:1];
    }
    self.truckTypeLabel.text = total;
    [self removeTruckLengthTypeView];
    [self setTabViewWithIndex:3];
    //调用刷新网络请求
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark --- 网络请求
//货源搜索数据
- (void)netLoadGoodsSearchWithIndex:(NSInteger)index{
    NSString *length = [HTUtils sortLengthDataDisplayStringWithArray:self.selectedLengthData];
    NSString *goosType = @"";
    if (self.selectedGoodsType != nil && ![self.selectedGoodsType.title isEqualToString:@"不限"]) {
        goosType = self.selectedGoodsType.title;
    }
    NSString *carType = @"";
    if (self.selectedTruckType != nil &&![self.selectedTruckType.title isEqualToString:@"不限"]) {
        carType = self.selectedTruckType.title;
    }
    [HTHttpRequestManager requestGoodsSearchWithStarname:self.startAddress endname:self.endAddress length:length goodstype:goosType cartype:carType cargotype:[NSString stringWithFormat:@"%d",self.isLessThanTruck]  page:[NSString stringWithFormat:@"%ld",index]  success:^(id  _Nullable responseObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        DBLog(@"货源搜索：%@",responseObject);
        if (!responseObject) {
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            return;
        }
        if (self.pageNumber == 1) {
            //代表是刷新的
            [self.dataSource removeAllObjects];
        }
        self.isauitd = [NSString stringWithFormat:@"%@",responseObject[@"isauitd"]];
        NSArray *result = responseObject[@"data"][@"data"];
        NSMutableArray *dataResult = [HTGoodSearchModel mj_objectArrayWithKeyValuesArray:result];
        [self.dataSource addObjectsFromArray:dataResult];
        NSDictionary *dic = responseObject[@"data"][@"meta"];
        self.refreshMoreModel = [HTRefreshMoreModel mj_objectWithKeyValues:dic[@"pagination"]];
        NSString *currentPage = self.refreshMoreModel.current_page;
        self.pageNumber = [currentPage integerValue];
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)loadMoreData{
    [self.tableView.mj_header endRefreshing];
    if (self.dataSource.count == 0) {
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        return;
    }
    self.pageNumber ++;
    if (self.refreshMoreModel && [self.refreshMoreModel.total integerValue] < self.pageNumber) {
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        return;
    }
    [self netLoadGoodsSearchWithIndex:self.pageNumber];
}
- (void)loadNewData{
    
    self.pageNumber = 1;
    [self.tableView.mj_footer endRefreshing];
    [self netLoadGoodsSearchWithIndex:1];
    
}


#pragma mark --- 上传
- (void)netLoadPostLocationWithAddress:(NSString *)address lat:(NSString *)lat lng:(NSString *)lng{
    [HTHttpRequestManager requestUploadAddressWithAddress:address lat:lat lng:lng success:^(id  _Nullable responseObject) {
        DBLog(@"上传地理位置:%@",responseObject);
    
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

@end
